package com.ba360.struts.action;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.ba360.portal.common.PortalConstants;
import com.ba360.portal.database.DBConnectionImpl;
import com.ba360.portal.database.dbo.SearchAgent;
import com.ba360.portal.database.dbo.User;
import com.ba360.portal.database.dbo.User_23Feb09;
import com.ba360.portal.util.Log;

/**
 * 
 */
public class SearchAgentAction extends Action {

	// --------------------------------------------------------- Instance
	// Variables

	// --------------------------------------------------------- Methods

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		Connection conn = null;
		Statement stmt = null;
		int userId = 0;

		try {
			Log.init(this.getClass());
			Log.info("SearchAgentAction");
			String action = request.getParameter(PortalConstants.ACTION);

			DBConnectionImpl dbConn = new DBConnectionImpl();
			HttpSession session = request.getSession();
			conn = dbConn.getConnection();
			stmt = conn.createStatement();

			if (session.getAttribute(PortalConstants.USER) != null) {
				userId = (int) ((User_23Feb09) session
						.getAttribute(PortalConstants.USER)).getUserId();
			}
			if (action != null) {
				if (action.equals(PortalConstants.CREATE_AGENT)) {
					adAgentInfo(stmt, form, request, userId);
				} else if (action.equals(PortalConstants.VIEW_AGENT)) {
					ArrayList searchAgents = getSearchAgents(stmt, request, userId);
					session.setAttribute("SEARCHAGENTS", searchAgents);
				} else if (action.equals(PortalConstants.EDIT_AGENT)) {
					ArrayList searchAgents = getEditSearchAgents(session, stmt, request, userId);
					session.setAttribute("EDITAGENT", searchAgents);
					return mapping.findForward(PortalConstants.PAGE_MODIFY);
				} else if (action.equals(PortalConstants.MODIFY_AGENT)) {
					updateAgentInfo(stmt, request, userId);
				} else if (action.equals(PortalConstants.DELETE_AGENT)) {
					deleteAgentInfo(stmt, request, userId);
				}
			}
		} catch (Exception e) {
			Log.error("Error in searching ad :" + e.getMessage());
			throw e;
		} finally {
			stmt.close();
			conn.close();
		}

		return mapping.findForward(PortalConstants.PAGE_SUCCESS);
	}

	private void adAgentInfo(Statement stmt, ActionForm searchForm,
			HttpServletRequest request, int userId) throws Exception {

		try{
			String keyWords = request.getParameter("keywords");
			int matchType = new Integer(request.getParameter("matchtype")).intValue();
			String timeFrame = request.getParameter("timeframe");

			Log.info("Adv Agent Contents: "+keyWords+"  "+ matchType);

	        String emailaddress = getEmailId(stmt, userId);
	        
	        Calendar cal = Calendar.getInstance();
	        
	        String DATE_FORMAT = "yyyy-MM-dd";
	        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);

	        stmt.executeUpdate("insert into search_agent (userid, keywords, matchtype, createddate, timeframe, emailaddress) values ("
							+ userId
							+ ",'"
							+ keyWords
							+ "',"
							+ matchType
							+ ",'"
							+ sdf.format(cal.getTime())
							+ "',"
							+ timeFrame
							+ ",'" 
							+ emailaddress + "')");

			stmt.close();
		} catch (Exception e) {
			Log.error("Error in searching ad :" + e.getMessage());
		}
	}

	private void updateAgentInfo(Statement stmt, HttpServletRequest request,
			int userId) throws Exception {

		try{
			String OrgKeyWords = request.getParameter("orgkeywords");
			String UpdKeyWords = request.getParameter("updkeywords");
			int matchType = new Integer(request.getParameter("matchtype")).intValue();
			String timeFrame = request.getParameter("timeframe");

			Log.info("Adv Agent Contents: " + UpdKeyWords + "  " + matchType);

	        Calendar cal = Calendar.getInstance();
	        
	        String DATE_FORMAT = "yyyy-MM-dd";
	        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);

	        stmt.executeUpdate("update search_agent set keywords='" + UpdKeyWords
					+ "', matchtype = " + matchType
					+ ", createddate = '" + sdf.format(cal.getTime())
					+ "', timeframe = " + timeFrame
					+ " where userid = " + userId
					+ " and keywords ='" + OrgKeyWords + "'");

			stmt.close();
		} catch (Exception e) {
			Log.error("Error in searching ad :" + e.getMessage());
		}
	}

	private void deleteAgentInfo(Statement stmt, HttpServletRequest request,
			int userId) throws Exception {

		try{
			String keywords = request.getParameter("keywords");

	        stmt.executeUpdate("delete from search_agent where userid = "
	        				+ userId
							+ " and keywords ='"
							+ keywords + "'");

			stmt.close();
		} catch (Exception e) {
			Log.error("Error in searching ad :" + e.getMessage());
		}
	}
	
	private ArrayList getEditSearchAgents(HttpSession session, Statement stmt,
			HttpServletRequest request, int userId) {

		ArrayList searchAgents = new ArrayList();
		int selectedRow = new Integer(request.getParameter("selectedrow")).intValue();

		try {

			if (session.getAttribute("SEARCHAGENTS") != null) {
				searchAgents = (ArrayList) session.getAttribute("SEARCHAGENTS");
			}
			if (searchAgents == null || searchAgents.size() == 0) {
				return null;
			} else {
				SearchAgent agent = (SearchAgent) searchAgents.get(selectedRow);
				searchAgents = new ArrayList();
				searchAgents.add(agent);
			}
		} catch (Exception excp) {
			Log.error("Error in getting search agents :" + excp.getMessage());
		}
		
		return searchAgents;
	}

	private ArrayList getSearchAgents(Statement stmt,
			HttpServletRequest request, int userId) {

		ArrayList searchAgents = new ArrayList();
		ResultSet rs = null;
		SearchAgent agent;
		
		try {

			rs = stmt.executeQuery("select * from search_agent where UserID=" + userId);

			while(rs.next()) {
				agent = new SearchAgent();
				agent.setKeywords(rs.getString("keywords"));
				agent.setMatchtype(rs.getInt("matchtype"));
				agent.setCreateddate(rs.getString("createddate"));
				agent.setTimeframe(rs.getString("timeframe"));
				searchAgents.add(agent);
			}
		} catch(Exception excp) {
			Log.error("Error in getting search agents :" + excp.getMessage());
		} finally {
			try {
				rs.close();
			} catch (SQLException sqlExcp) {
				Log.error("Error in getting search agents :" + sqlExcp.getMessage());
			}
		}
		
		return searchAgents;
	}

	private String getEmailId(Statement stmt, int userId) {

		String emailaddress = "";
		ResultSet rs = null;

		try {

			rs = stmt.executeQuery("select emailaddress from userinfo where UserID=" + userId);

			if(rs.next()) {
				emailaddress = rs.getString("emailaddress");
			}
		} catch(Exception excp) {
			Log.error("Error in getting emailaddress :" + excp.getMessage());
		} finally {
			try {
				rs.close();
			} catch (SQLException sqlExcp) {
				Log.error("Error in getting emailaddress :" + sqlExcp.getMessage());
			}
		}
		
		return emailaddress;
	}
}